package com.funcourse.demo.wechat.client.web;

import com.funcourse.demo.api.ApiSystemConstants;
import com.funcourse.demo.wechat.client.web.io.resp.JsCode2TokenResponse;
import com.funcourse.demo.wechat.conf.WechatConfiguration;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class JsCode2TokenGetter {

  private static final String ADDRESS = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={appId}&secret={secret}&code={jsCode}&grant_type=authorization_code";
  private static final String AUTH_TYPE = "authorization_code";
  @Autowired
  RestTemplate restTemplate;
  @Autowired
  HttpServletRequest httpServletRequest;
  String grantType = AUTH_TYPE;

  public JsCode2TokenResponse code2Session(String jsCode) {
    final Object attribute = httpServletRequest
        .getAttribute(ApiSystemConstants.SERVLET_ATTR_WECHAT_CONFIG);
    WechatConfiguration weletConfiguration = (WechatConfiguration)attribute;
    return restTemplate.getForObject(ADDRESS, JsCode2TokenResponse.class,
        weletConfiguration.getAppId(), weletConfiguration.getAppSecret(), jsCode);
  }


}
